import api from '@/common/api.js'
import global from '@/common/global.js'

const { SYS_CODE: sysCode, WE_CHART_APPID: appId } = global

export const checkHosId = function () {
  return new Promise(resolve => {
    const hosId = uni.getStorageSync('hosId')
    if (hosId) {
      resolve(hosId)
    } else {
      api
        .gethosList({
          sysCode,
          divisionCode: '',
          searchStr: '',
          page: 1,
          pageSize: 20,
        })
        .then(({result}) => {
          if (result && result.length) {
            const {hosId, hosName} = result[0];
            uni.setStorageSync('hosId', hosId);
            uni.setStorageSync('hosName', hosName);
            resolve(hosId)
          }
        })
    }
  })
}

export const getAppSct = function (hosId) {
  // 获取信息
  return api
    .getConfigurationParam({
      sysCode,
      hosId,
    })
    .then(res => {
      uni.setStorageSync('configurationParam', res.data.list)
      const appSct = res.data.list.find(item => item.paramCode === 'WECHAT_MINI_SCT').paramValue
      uni.setStorageSync('appSct', appSct)
      return Promise.resolve(appSct)
    })
}

export const checkAppSct = async function () {
  // const hosId = uni.getStorageSync('hosId')
  return new Promise(resolve => {
    checkHosId().then(hosId => {
      const appSct = uni.getStorageSync('appSct')
      if (appSct) {
        resolve(appSct)
      } else {
        getAppSct(hosId).then(appSct => {
          resolve(appSct)
        })
      }
    })
  })
}

export const outLogin = function () {
  const appSct = uni.getStorageSync('appSct')
  uni.clearStorageSync()
  uni.clearStorage()
  uni.setStorageSync('appSct', appSct)
  setTimeout(() => {
    uni.reLaunch({
      url: '/pages/home/my',
    })
  }, 1000)
} 
